package myClassLoader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MicClassLoader extends ClassLoader {

	protected synchronized Class<?> findClass(String className)
			throws ClassNotFoundException {
		Class<?> result;
		byte classData[];

		classData = getClassFromAddedClassPaths(className);
		if (classData == null) {
			throw new ClassNotFoundException();
		}

		result = super.defineClass("myClassLoader.TestModule", classData, 0,
				classData.length);
		if (result == null)
			throw new ClassFormatError();
		resolveClass(result);

		return result;
	}

	private byte[] getClassFromAddedClassPaths(String className) {
		try {

			File f = new File(className);
			if (f.exists()) {
				FileInputStream fis = new FileInputStream(f);
				return createByteArray(fis);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private byte[] createByteArray(InputStream in) throws IOException {
		final int bufferSize = 2048;
		byte result[] = new byte[bufferSize];

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int len = 0;
		while ((len = in.read(result)) != -1)
			out.write(result, 0, len);
		return out.toByteArray();
	}

}
